package com.carpedil.shirodemo.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carpedil.shirodemo.common.util.TreeUtil;
import com.carpedil.shirodemo.system.mapper.OperatorMapper;
import com.carpedil.shirodemo.system.model.Menu;
import com.carpedil.shirodemo.system.model.Operator;
import com.carpedil.shirodemo.system.service.IMenuService;
import com.carpedil.shirodemo.system.service.IOperatorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 服务实现类
 *
 * @author carpedil
 * @since 2021-01-05
 */
@Service
public class OperatorServiceImpl extends ServiceImpl<OperatorMapper, Operator>
    implements IOperatorService {
  @Autowired private OperatorMapper operatorMapper;
  @Autowired private IMenuService menuService;

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void insert(Operator operator) {
    operatorMapper.insert(operator);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void updateOperator(Operator operator) {
    operatorMapper.updateById(operator);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void deleteById(Integer operatorId) {
    operatorMapper.deleteById(operatorId);
  }

  @Override
  public List<Menu> getAllMenuAndOperatorTree() {
    // 获取所有操作权限
    // mybatis-plus自带方法
    List<Operator> operators = operatorMapper.selectList(null);
    // mybatis-plus自带方法
    List<Menu> menus = menuService.list(null);

    // 获取功能权限树时, 菜单应该没有复选框
    for (Menu menu : menus) {
      menu.setCheckArr(null);
    }

    // 将平级集合转换为带有children的树结构
    List<Menu> menuTree = TreeUtil.toTree(menus, "menuId", "parentId", "children", Menu.class);

    // 获取Menu树结构的children子集
    // 根菜单树不带有url，也就不具有权限功能，具体的权限是放在次一级的菜单中
    // 比如用户管理-->用户的增删改等操作，角色管理-->角色的增删改等操作
    List<Menu> menuLeafNode = TreeUtil.getAllLeafNode(menuTree);

    // 将操作权限，挂载到菜单的树形结构上
    for (Menu menu : menuLeafNode) {
      List<Menu> children = menu.getChildren();
      if (children == null) {
        children = new ArrayList<>();
      }

      for (Operator operator : operators) {
        if (menu.getMenuId().equals(operator.getMenuId())) {

          // 将操作权限转化为 Menu 结构. 由于操作权限可能与菜单权限的 ID 值冲突, 故将操作权限的 ID + 10000. 使用操作权限的 ID 时再减去这个数
          Menu temp = new Menu();
          temp.setMenuId(operator.getOperatorId() + 10000);
          temp.setParentId(operator.getMenuId());
          temp.setMenuName(operator.getOperatorName());
          children.add(temp);
        }
      }
      menu.setChildren(children);
    }
    return menuTree;
  }
}
